import sys
import time
print(23421)
import mysql.connector
import threading
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QApplication,QHBoxLayout,QLineEdit,QTextEdit,QDesktopWidget
from PyQt5.QtGui import QTextCursor
from PyQt5.QtCore import pyqtSignal, QObject
print(23422)
import pymysql
from contextlib import contextmanager
import mysql.connector
from mysql.connector import pooling
print(mysql.connector.__version__)
import queue
print(23423)
from selenium.webdriver.support.ui import WebDriverWait
import os
print(23424)
from MySQLHelper import MySQLHelper
print(23425345)
from public import human_move_and_click
print(23424)

from public import human_move_and_move
print(234214)
from public import human_clear
print(234224)
from public import human_type
print(234324)
from public import process_captcha_image_text
print(204)
from public import getdrvier
print(0)
a=234+23
from PyQt5.QtWidgets import QApplication, QMessageBox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import logging
import traceback
import os
import sys
from selenium.webdriver.common.by import By

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import random
from random import randint
from selenium.webdriver.common.keys import Keys

from public import except_to_db_rpa 
logging.basicConfig(filename=r'.\error.log', level=logging.ERROR)
error_details=''
print(f"a = {a}")
heartsleep=1
# 添加这行来保持程序运行
# input("按回车键退出...")
 

class MessageSender(QObject):
    textUpdateSignal = pyqtSignal(str)
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.dbhelper=MySQLHelper()
        print(1)
        layout_h = QHBoxLayout()
        print(2)
        self.lock=threading.Lock()
        self.resume_button = QPushButton("启动任务")
        self.resume_button.clicked.connect(self.resume_thread)
        self.pause_button = QPushButton("停止任务")
        self.pause_button.clicked.connect(self.pause_thread)
        self._pause_event = threading.Event()
        self._pause_event.clear()  #
        self.setGeometry(300, 300, 800, 500)
        self.setWindowTitle('跟价改价-RPA')
        text_layout = QHBoxLayout()
        print(1)
        
        self.textmemo = QTextEdit()
        text_layout.addWidget(self.textmemo)
        self.sender = MessageSender()
        self.sender.textUpdateSignal.connect(self.textmemo.append)
        layout_h.addWidget(self.resume_button)

        self.textmemo.append(
            '本系统负责跟价改价')
        # self.textmemo.append(
        #     '请在第一个打开的谷歌浏览器登录店小秘ebay账号，在第二个浏览器登录aliexpress店小秘账号')
        # layout_h.addWidget(self.pause_button)
        self.sender = MessageSender()
        print(11)
        
        self.sender.textUpdateSignal.connect(self.textmemo.append)
   
        main_layout = QVBoxLayout()
        main_layout.addLayout(layout_h)
        main_layout.addLayout(text_layout)
        self.setLayout(main_layout)
        self.thread = []
        shoptypes = ['ebay', 'ali']
        self.driverlist=[]
        # shoptype = ['ali']
        print(13)
        

        # shoptype = ['ebay']

        
        try:
            for index, sptype in enumerate(shoptypes):
                lockdianxiaomi = threading.Lock()
                sql=f"SELECT cfgcode,cfgvalue FROM configure where cfgmemo='{sptype}account'  "
                results=self.dbhelper.query(sql)
                skulist2=self.get_itemids(sptype)
                account=results[0]['cfgcode']
                password=results[0]['cfgvalue']
                driver = getdrvier()
                self.driverlist.append(driver)
                if sptype == 'ali'  :
                    driver.get('https://www.dianxiaomi.com/smtProduct/index.htm')
                if sptype == 'ebay'  :
                    driver.get('https://www.dianxiaomi.com/ebayProduct/index.htm?dxmState=online')
                    # driver.get(
                wait=WebDriverWait(driver,10)

                username=wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="exampleInputName"]')))
                human_move_and_move(driver,username)
                human_type(username,account)
                passwordelement=wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="exampleInputPassword"]')))
                human_move_and_move(driver,passwordelement)
                human_type(passwordelement,password)    
                # //*[@id="exampleInputName"]
                for ix in range(12):
                    if '欢迎登录' in driver.page_source:
                        validcode=process_captcha_image_text(driver,'//*[@id="verifyImgCode"]')
                        verycodeelement=wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="verifyCode"]')))
                        human_move_and_move(driver,verycodeelement)
                        human_clear(verycodeelement)
                        human_type(verycodeelement,validcode['data']['recognition'])  
                        self.sender.textUpdateSignal.emit( f'{account} 账户第{ix+1}次尝试登录，验证码{validcode["data"]["recognition"]}')  
                        login=wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="loginBtn"]')))
                        human_move_and_click(driver,login)
                        time.sleep(2)


                # 登录了
            tis = threading.Thread(target=self.parse_next_url,
                                    args=(  self.driverlist,lockdianxiaomi,))
            self.thread.append(tis)    
            self.resume_thread()
        except  Exception as e:
            print(e)
            error_details = traceback.format_exc()
            except_to_db_rpa(self,self.dbhelper,error_details)
        #     # tis.start()
    def pause_thread(self):
        # self._pause_event.clear()
        ixx = 2

    def resume_thread(self):
        for i in range(len(self.thread)):
            self.thread[i].start()
        self.resume_button.setEnabled(False)
        # self._pause_event.set()
    



    
    def get_itemids(self, shoptype):
        """
        获取 ebay,ali 商品的 itemid 列表，并处理逗号分隔的情况
        """
        skuslist = []
        try:
            # 获取跟价商品
            sql =f"""     SELECT itemid, price FROM follow_price WHERE shop_type = '{shoptype}' AND itemid IS NOT NULL AND LENGTH(itemid) >5   """
            follow_items=self.dbhelper.query(sql)
            for item in follow_items:
                itemid = item['itemid'].replace('，', ',')
                itemid = itemid.replace(';', ',')
                minprice = item['price']
                if itemid=='226271599166':
                    a=123
                # 处理逗号分隔的 itemid
                for row in itemid.split(','):
                    row = row.strip()
                    if not row:
                        continue
                        
                    try:
                        # 获取历史记录
                        history_sql =f"""
                            SELECT toprice 
                            FROM sku_keywords_history 
                            WHERE sku = {row} 
                            ORDER BY opdate DESC 
                            LIMIT 3
                        """
                        # cursor.execute(history_sql)
                        # history = cursor.fetchone()
                        history=self.dbhelper.query(history_sql)
                        intfollow = 0
                        if not history:
                            intfollow = 1
                        else:
                            if abs(minprice - 5 - history[0]['toprice']) > 0.1:
                                intfollow = 1
                                
                        if intfollow == 1 and minprice != 0:
                            # 检查是否已存在相同的记录
                            exists = False
                            for existing in skuslist:
                                if existing['sku'] == row and existing['price'] == minprice - 5:
                                    exists = True
                                    break
                                    
                            if not exists:
                                skuslist.append({
                                    "sku": row, 
                                    "price": minprice - 5
                                })
                                self.sender.textUpdateSignal.emit(f'当前：{row} 价格{minprice - 5}')
                                
                    except Exception as e:
                        error_details = traceback.format_exc()
                        except_to_db_rpa(self,self.dbhelper,error_details)
                        print(f"Error processing row {row}: {str(e)}")
                        
        except Exception as e:
                print(f"Error in get_itemids: {str(e)}")
                error_details = traceback.format_exc()
                except_to_db_rpa(self,self.dbhelper,error_details)

            
        return skuslist
    def simulateelem(self,driver,element):
        
        try:
            actions = ActionChains(driver)
            
            # 随机选择一个偏移量
            offset_x = randint(-5, 5)
            offset_y = randint(-5, 5)
            
            # 移动到元素附近
            actions.move_to_element_with_offset(element, offset_x, offset_y)
            actions.move_to_element(element)
            time.sleep(heartsleep *random.random())
            
            # 点击
            # actions.click()
            actions.perform()
            # time.sleep(heartsleep* 2 *random.random())
            # 点击后的随机等待
            
        except Exception as e:
            print(f"点击操作失败: {str(e)}")  





    def parsedb(self,  sku, curprice,shoptype):
        try:
            query = f'select ifnull(toprice,0) as toprice from sku_keywords_history where sku="{sku}" order by opdate desc limit 1 '
            
            results_a = self.dbhelper.query(query)
            fromprice = 0
            if results_a:
                fromprice = results_a[0]['toprice']
            query = f'insert into sku_keywords_history(ebay,sku,fromprice,toprice,opdate) values(1,"{sku}",{fromprice},{curprice},now()) '
            if shoptype=='ali': 
                query = f'insert into sku_keywords_history(ali,sku,fromprice,toprice,opdate) values(1,"{sku}",{fromprice},{curprice},now()) '
            self.dbhelper.execute(query)
           
            self.sender.textUpdateSignal.emit(f'{sku} {fromprice}->{curprice}改价成功')
        except Exception as e:
            print('parsedb',e)
            error_details = traceback.format_exc()
            except_to_db_rpa(self,self.dbhelper,error_details)

    def find_element_in_frames(self,driver):
        # 等待页面加载完成
        try:
            WebDriverWait(driver, 10).until(
                lambda d: d.execute_script('return document.readyState') == 'complete'
            )
            
            # 打印页面源码，用于调试
            # print("Page source:", driver.page_source)
            
            # 获取所有 iframe
            iframes = driver.find_elements(By.TAG_NAME, "iframe")
            print(f"找到 {len(iframes)} 个 iframe")
            
            for iframe in iframes:
                try:
                    # 打印 iframe 的属性，帮助调试
                    print("iframe ID:", iframe.get_attribute("id"))
                    print("iframe Name:", iframe.get_attribute("name"))
                    
                    # 切换到 iframe
                    driver.switch_to.frame(iframe)
                    
                    # 查找元素
                    element = driver.find_element(By.ID, "productIdSearch")
                    print("找到元素!")
                    return element
                    
                except Exception as e:
                    print(f"在当前 iframe 中查找失败: {str(e)}")
                    driver.switch_to.default_content()
                    error_details = traceback.format_exc()
                    except_to_db_rpa(self,self.dbhelper,error_details)
                    continue
                    
 
        except Exception as e:
            print(f"发生错误: {str(e)}")
            error_details = traceback.format_exc()
            except_to_db_rpa(self,self.dbhelper,error_details)

            
        return None
    def getexcept(self,emsg):
        spec = [
            "'"
            '<', '>', '$', '*', '&', '%', '.', '"', '+', '-', '@', '"', '\\',
            '(', ')', ' ', '#', '.', '//', '#'
        ]
        for sp in spec:
            if sp in emsg:
                emsg = emsg.replace(sp, ' ')
        emsg = emsg.replace('"', '')
        return emsg.strip()
    def click_aliproduct_id_search(self,driver,xpaths):
        bok=False
        actions = ActionChains(driver)
        try:
        # 先等待元素可见
            wait = WebDriverWait(driver, 10)
            try:
                element = wait.until(
                EC.element_to_be_clickable((By.ID, "productIdSearch")))
                element.click()
                return True

            except:
                try:# 如果常规点击失败，尝试 JavaScript 点击
                    driver.execute_script("arguments[0].click();", element)
                    bok=True
                    return True
                except Exception as e:  
                    error_details = traceback.format_exc()
                    except_to_db_rpa(self,self.dbhelper,error_details)

                    print(e)
            # 等待点击后的效果（根据实际情况调整）
            for xpath in xpaths:
                try:
                    # 如果常规点击失败，尝试 JavaScript 点击
                    element = wait.until(
                    EC.element_to_be_clickable((By.XPATH, xpath)))
                    self.simulateelem(driver, element)
                    element.click()
                    time.sleep(0.5)
                    return True
                except Exception as e:
                    print(e)       
        except Exception as e:
            print(f"点击产品ID搜索失败: {str(e)}")
            error_details = traceback.format_exc()
            except_to_db_rpa(self,self.dbhelper,error_details)
        return False
    def parse_next_url(self,  driver,lockdianxiaomi):
        waitseconds=30
        ebaysearch = None 
        alisearch = None
        with self.lock:
            search_data = self.read_search_file()
            ebaysearch = search_data['ebaysearch']  
            alisearch = search_data['alisearch']
        skulist=[]
        # 轮流改价，
        while True:
            # time.sleep(20)
            shoptypes = ['ebay', 'ali']
            for index, shoptype in enumerate(shoptypes):
                driver=self.driverlist[index]
                actions=ActionChains(driver)
                current_time_stamp = time.time()
                local_time_struct = time.localtime(current_time_stamp)
                with self.lock:
                    skulist = self.get_itemids(shoptype)
                hour = local_time_struct.tm_hour
                minute = local_time_struct.tm_min
                second = local_time_struct.tm_sec
                hrandom = random.randint(1, 30)
                print(shoptype,local_time_struct)
                self.sender.textUpdateSignal.emit(f'{shoptype} {hour}时{minute}分{second}秒,准备打印需要跟价的产品清单')
                for       skux in skulist:
                    self.sender.textUpdateSignal.emit(f'{skux}')
                b_cap = 0
                if hour >= 8:
                    b_cap = 1
                # if shoptype == 'ali' and b_cap == 1:
                if shoptype == 'ali'  :
                    if len(skulist) > 0:
                        lockdianxiaomi.acquire()

                        driver.get('https://www.dianxiaomi.com/smtProduct/index.htm')
                        wait = WebDriverWait(driver, 10)  # 最多等待10秒
                        print(alisearch)
                        time.sleep(1)
                        xpathp=['//*[@id="productIdSearch"]',
                                '/html/body/div[30]/div[2]/div[2]/div[2]/div[2]/div[2]/a[3]'
                                ]
                        wait = WebDriverWait(driver, 10)  # 最多等待10秒
                        for xp1 in xpathp:
                            try:
                                element = wait.until(
                                EC.presence_of_element_located((By.XPATH, xp1)))
                                # 清除元素内原有的内容
                                element.click()
                                time.sleep(1)
                                break
                            except Exception as e:
                                print('ali找itemid',  e)
                                error_details = traceback.format_exc()
                                except_to_db_rpa(self,self.dbhelper,error_details)

                        alix=['/html/body/div[30]/div[2]/div[2]/div[2]/div[2]/div[2]/a[3]']
                        alix.append(alisearch)
                        # find_element_in_frames(driver)
                        # click_aliproduct_id_search(driver,alix)
                        
                        
                    # element.click()
                        for i, sku in enumerate(skulist):
                            # 输入商品编码，进行查询
                            try:
                                # 搜索内容
                                logging.info(f'{i}:1')
                                wait = WebDriverWait(driver, 10)  # 最多等待10秒

                                element = wait.until(
                                    EC.presence_of_element_located((By.ID, "searchValue")))
                                # 清除元素内原有的内容
                                human_clear(element)
                                # 向元素内输入新的内容'hello'

                                human_type(element,sku['sku'])
                                element.send_keys(Keys.ENTER)

                                # human_type(element,Keys.ENTER)
                                self.simulateelem(driver, element)
                                logging.info(f'{i}:2')

                                # try:
                                #     close_button = driver.find_element(By.CSS_SELECTOR,
                                #                                        'button.close')
                                #     close_button.click()
                                # except Exception as e:
                                #     print(e)
                                # 点击修改按钮，弹出窗口，改价  simulateelem(actions, element)

                                element_editprice = driver.find_element(
                                    By.XPATH,
                                    '//*[@id="smtSysMsg"]/tr[1]/td[5]/table/tbody/tr/td[2]/span/a'
                                )
                                self.simulateelem(driver, element_editprice)
                                try:
                                    element_editprice.click()
                                except Exception as e:
                                    print(e)
                                    error_details = traceback.format_exc()
                                    except_to_db_rpa(self,self.dbhelper,error_details)

                                # 输入新价格
                                # element_newprice = wait.until(
                                #     EC.presence_of_element_located((By.CLASS_NAME, 'w80')))
                                logging.info(f'{i}:3')
                                element_newprice = None
                                xpath1 = '//*[@id="smtEditPriceTable"]/table/tbody/tr/td[2]/input'
                                xpath2 = '//*[@id="smtEditPriceTable"]/div/table/tbody/tr[2]/td[4]/input'
                                try:
                                    element_newprice = wait.until(
                                        EC.presence_of_element_located((By.XPATH, xpath2)))
                                except Exception as e:
                                    print(e)
                                    error_details = traceback.format_exc()
                                    except_to_db_rpa(self,self.dbhelper,error_details)

                                    try:        
                                        element_newprice = wait.until(
                                            EC.presence_of_element_located((By.XPATH, xpath1)))
                                        oldprice=element_newprice.get_attribute('value')    
                                    except Exception as e:
                                        print(e)
                                        error_details = traceback.format_exc()
                                        except_to_db_rpa(self,self.dbhelper,error_details)
                                finally:
                                    self.simulateelem(driver, element_newprice)
                                    element_newprice.click()

                                logging.info(f'{i}:4')
                                human_clear(element_newprice)
                                # element_newprice.clear()
                                fv = sku['price']
                                # element_newprice.send_keys(f"{fv}")
                                # element_newprice.send_keys(Keys.ENTER)
                                human_type(element_newprice,f"{fv}")
                                time.sleep(0.5)
                                logging.info(f'{i}:45')

                                element_determine = wait.until(
                                    EC.presence_of_element_located((
                                        By.XPATH,
                                        '//*[@id="smtEditPriceModal"]/div[2]/div/div[3]/button[1]'
                                    )))
                                self.simulateelem(driver, element_determine)
                                logging.info(f'{i}:5')

                                element_determine.click()
                                time.sleep(2)
                                inttimes = 0
                                while True:
                                    try:
                                        # 使用 find_elements_by_id 方法查找元素（此处定位方式可按需替换），返回元素列表
                                        element_determine = driver.find_element(
                                            By.XPATH,
                                            '//*[@id="smtEditPriceModal"]/div[2]/div/div[3]/button[1]'
                                        )
                                        if len(element_determine) > 0:
                                            print("元素仍然存在")
                                        else:
                                            print("元素已不存在")
                                            break
                                    except Exception as e:
                                        print("元素已不存在")
                                        error_details = traceback.format_exc()
                                        # except_to_db_rpa(self,self.dbhelper,error_details)
                                        time.sleep(3)
                                        break
                                    # 每隔1秒检查一次，你可以根据实际情况调整时间间隔
                                    inttimes += 1
                                    if inttimes > 5:
                                        element_cancel = driver.find_element(
                                            By.XPATH,
                                            '//*[@id="smtEditPriceModal"]/div[2]/div/div[3]/button[2]'
                                        )
                                        element_cancel.click()
                                # 处理数据库
                                self.parsedb( sku['sku'], sku['price'],shoptype)
                            except Exception as e:
                                print(e)
                                error_details = traceback.format_exc()
                                except_to_db_rpa(self,self.dbhelper,f"{error_details},对应sku是 {sku['sku']}")

                        lockdianxiaomi.release()
                # if shoptype == 'ebay' and b_cap == 1:

                if shoptype == 'ebay'  :   
                    
                    if len(skulist) > 0:
                        lockdianxiaomi.acquire()

                        # 点击sku 登录密码 20241121Aa
                        wait = WebDriverWait(driver, 10)  # 最多等待10秒 #登录密码 20241121Aa
                        try:
                            driver.get(
                                'https://www.dianxiaomi.com/ebayProduct/index.htm?dxmState=online'
                            )
                            # driver.get(
                            #     'https://www.dianxiaomi.com/ebayProduct/index.htm?dxmState=online')
                            time.sleep(0.1)
                            element = wait.until(
                                EC.presence_of_element_located(
                                    (By.XPATH, ebaysearch)))
                            
                            # 模拟点击元素,上述代码，模拟点SKU
                            element.click()
                        except Exception as e:
                            print(f"出现其他异常: {e}")
                            error_details = traceback.format_exc()
                            except_to_db_rpa(self,self.dbhelper,error_details)

                        for i, sku in enumerate(skulist):
                            # # for i in range(5):
                            #     sku = skulist[0]
                            #     sku['sku'] = 'PZTC70SX3@#14'
                            #     sku['price'] = '27.31'
                            try:
                                element = WebDriverWait(driver, 10).until(
                                    EC.element_to_be_clickable((By.ID, "searchValue")))
                                self.simulateelem(driver, element)
                                # element.clear()
                                human_clear(element )
                                element.send_keys(sku['sku'])
                                self.simulateelem(driver, element)
                                element.send_keys(Keys.ENTER)
                                # human_type(element,Keys.ENTER)

                                self.simulateelem(driver, element)
                                xpath_price_first = '//*[@id="ebaySysMsg"]/tr/td[5]/table/tbody/tr/td[2]/div/div'
                                # 首先，实现点击价格，让价格可以高亮度显示
                                xpath_static_price = '/html/body/div[36]/div[2]/div[2]/div[4]/div[2]/div[2]/div[1]/table/tbody/tr/td[5]/table/tbody/tr/td[2]/div/div'
                                element_price_static = wait.until(
                                    EC.element_to_be_clickable(
                                        (By.XPATH, xpath_static_price)))
                                self.simulateelem(driver, element_price_static)
                                actions.double_click(element_price_static).perform()
                                xpath_price = [
                                    '/html/body/div[36]/div[2]/div[2]/div[4]/div[2]/div[2]/div[1]/table/tbody/tr[1]/td[5]/table/tbody/tr/td[2]/div/div[2]/input',
                                    '/html/body/div[36]/div[2]/div[2]/div[4]/div[2]/div[2]/div[1]/table/tbody/tr/td[5]/table/tbody/tr/td[2]/div/div[2]/input',
                                    '//*[@id="varintUpdateInput"]'
                                ]
                                isuccess = 0
                                for xpx in xpath_price:
                                    if isuccess == 1:
                                        continue
                                    try:
                                        element_price = wait.until(
                                            EC.element_to_be_clickable((By.XPATH, xpx)))
                                        #  登录密码 20241121Aa
                                        self.simulateelem(driver, element_price)
                                        actions.double_click(element_price).perform()
                                        element_price.send_keys(sku['price'])
                                        value1 = element_price.get_attribute('value')
                                        if abs(float(value1) - float(sku['price'])) < 0.01:
                                            isuccess = 1
                                    except Exception as e:
                                        print(f"出现其他异常: {e}")
                                        error_details = traceback.format_exc()
                                        except_to_db_rpa(self,self.dbhelper,error_details)


                                time.sleep(0.1)
                                # 上面代码输入新价格，后面代码更新价格 登录密码 20241121Aa
                                wait = WebDriverWait(driver, 10)
                                xpath_submitprice = [
                                    '//*[@id="priceBotton"]/button[1]',
                                    '/html/body/div[36]/div[2]/div[2]/div[4]/div[2]/div[2]/div[1]/table/tbody/tr/td[5]/table/tbody/tr/td[2]/div/div[2]/button[1]',
                                    '//*[@id="priceBotton"]',
                                    '/html/body/div[36]/div[2]/div[2]/div[4]/div[2]/div[2]/div[1]/table/tbody/tr[1]/td[5]/table/tbody/tr/td[2]/div/div[2]/input'
                                ]
                                intsubmitsuccess = 0
                                for xp2 in xpath_submitprice:
                                    if intsubmitsuccess == 1:
                                        continue
                                    try:
                                        element = wait.until(
                                            EC.presence_of_element_located(
                                                (By.XPATH, xp2)))
                                        self.simulateelem(driver, element)
                                        # actions.click(element).perform()
                                        actions.move_to_element(element)
                                        time.sleep(0.1)
                                        actions.double_click(element).perform()
                                        intsubmitsuccess = 1
                                    except Exception as e:
                                        print("元素已不存在")
                                        error_details = traceback.format_exc()
                                        except_to_db_rpa(self,self.dbhelper,error_details)

                                        # break
                                        time.sleep(0.1)
                                while True:
                                    try:
                                        # 使用 find_elements_by_id 方法查找元素（此处定位方式可按需替换），返回元素列表
                                        # 再去找这个更新按钮，如果找到，就不进行下一步；
                                        # 如果没有找到，就进入下一步
                                        for xp2 in xpath_submitprice:
                                            element = driver.findelement(By.XPATH, xp2)
                                            if len(element) > 0:
                                                print("元素仍然存在")
                                            else:
                                                print("元素已不存在")
                                                break
                                    except Exception as e:
                                        print("元素已不存在")
                                        error_details = traceback.format_exc()
                                        # except_to_db_rpa(self,self.dbhelper,error_details)

                                        time.sleep(0.1)
                                        break
                                self.parsedb( sku['sku'], sku['price'],shoptype)
                                time.sleep(0.1)

                            except Exception as e:
                                error_details = traceback.format_exc()
                                except_to_db_rpa(self,self.dbhelper,error_details)

                                print('*' * 100)
                                print(e)
                                print('*' * 100)
                        lockdianxiaomi.release()
            
            time.sleep(waitseconds)
    def element_to_be_clickable_and_inputable(self,locator):
        def _predicate(driver):
            element = EC.presence_of_element_located(locator)(driver)
            if element and element.is_displayed() and element.is_enabled() and element.tag_name in ['div','INPUT', 'TEXTAREA']:
                return element
            else:
                return False
        return _predicate
    def read_search_file(self):
        search_data = {}
        try:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建search.txt的完整路径
            full_path = os.path.join(current_dir, 'search.txt')
            with open(full_path, 'r', encoding='utf-8') as file:
                for line in file:
                    # Strip whitespace and split by '='
                    line = line.strip()
                    if '=' in line:
                        key, value = line.split('=', 1)
                        search_data[key.strip()] = value.strip()

        except Exception as e:
            print(f"An error occurred: {e}")
            error_details = traceback.format_exc()
            except_to_db_rpa(self,self.dbhelper,error_details)


        return search_data

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())
